﻿#include "rtspcodecwidget.h"

QImageProvider::QImageProvider() : QQuickImageProvider(QQuickImageProvider::Image)
{

}
/*-------------------------------------------
*
* 图片代理
*
---------------------------------------------*/
QImage QImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
    return voideImg;
    Q_UNUSED(id)
    Q_UNUSED(size)
    Q_UNUSED(requestedSize)
}

RtspCodecWidget::RtspCodecWidget(QWidget * parent)
    : QWidget(parent),
      m_imageProvider(0)
{
    m_rtspCodec = new RtspCodecThread(this);
    connect(m_rtspCodec, SIGNAL(receiveImage(const QImage&)), this, SLOT(updateImage(const QImage&)));

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(checkVideo()));
    timer->start(10000);

    m_imageProvider = new QImageProvider();
}

RtspCodecWidget::~RtspCodecWidget()
{
    close();
}

QImageProvider *RtspCodecWidget::imageProvider() const
{
    return m_imageProvider;
}
/*-------------------------------------------
*
* 更新图片
*
---------------------------------------------*/
void RtspCodecWidget::updateImage(const QImage &image)
{
    m_imageProvider->voideImg = image;
    emit updateVideo();
}
/*-------------------------------------------
*
* 检查连接
*
---------------------------------------------*/
void RtspCodecWidget::checkVideo()
{
    if(m_rtspCodec->getLastTime().secsTo(QDateTime::currentDateTime()) >= 30)
    {
        restart();
    }
}
/*-------------------------------------------
*
* 打开视频
*
---------------------------------------------*/
void RtspCodecWidget::open(const QString &url)
{
    m_rtspCodec->setUrl(url);
    m_rtspCodec->play();
    m_rtspCodec->start();
}
/*-------------------------------------------
*
* 关闭
*
---------------------------------------------*/
void RtspCodecWidget::close()
{
    if (m_rtspCodec->isRunning())
    {
        m_rtspCodec->stop();
        m_rtspCodec->quit();
        m_rtspCodec->wait(500);
    }
    QTimer::singleShot(1, this, SLOT(clear()));
}
/*-------------------------------------------
*
* 重启
*
---------------------------------------------*/
void RtspCodecWidget::restart()
{
    close();
    QTimer::singleShot(100, this, SLOT(open()));
}
